<template>
	<view class="layout">
		<wd-navbar title="流程卡扫码"  left-text="返回" @click-left="uni.navigateBack" left-arrow/>
		<wd-form ref="form" class="form" :model="formState">
			<wd-cell-group border>
			<wd-input 
				label="批次号" 
				prop="batchNumber" 
				v-model="formState.batchNumber"
				placeholder="点击右侧图标或按PDA扫描键扫码" 
				:rules="[{ required: true, message: '请输入批次号' }]" 
				@clicksuffixicon="onScan"
				@click="onScan"
				suffix-icon="qrcode" 
				readonly
			/>
				<wd-input 
					label="流程卡号" 
					prop="processCardId" 
					v-model="formState.processCardId"
					placeholder="通过批次号自动获取" 
					readonly
					disabled
				/>
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" @click="onSubmit" block>提交</wd-button>
			</view>
		</wd-form>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, onUnmounted, reactive, ref } from 'vue';
	import { C91330326Ma287Bmm6JService, ProcessService } from '@/services';
	import { useToast } from '@/uni_modules/wot-design-uni';
	import useApp from '@/stores/app';
	const app = useApp();
	const toast = useToast();

	const show = ref(true);
	const formState = reactive({
		batchNumber: '', // 批次号
		processCardId: '', // 流程卡号
	});

	const qrcode = async (code : string) => {
		try {
			console.log('PDA扫码接收到批次号数据:', code);
			
			if (!code) {
				toast.error('扫码数据为空');
				return;
			}
			
			// 设置扫到的批次号
			formState.batchNumber = code;
			
			// 查询流程卡号
			await queryProcessCardId(code);
		} catch (error) {
			toast.error('处理批次号失败');
			console.error('处理批次号失败:', error);
		}
	}
	
	// 根据批次号查询流程卡号
	const queryProcessCardId = async (batchNumber: string) => {
		if (!batchNumber || batchNumber.trim() === '') {
			formState.processCardId = '';
			app.code = '';
			return;
		}
		
		try {
			// 显示加载状态
			toast.loading('查询流程卡详细信息中...');
			
			// 调用接口根据批次号查询流程卡详细信息
			const result = await ProcessService.getProcessCardDetailByBatch(batchNumber.trim());
			
			if (result.code === 200 && result.data && result.data.id) {
				// 从返回的数据中提取 id 作为流程卡号
				formState.processCardId = result.data.id;
				app.code = result.data.id; // 设置全局流程卡号
				toast.success('查询成功！');
				console.log('批次号:', batchNumber, '对应流程卡号:', result.data.id);
				console.log('流程卡详细信息:', result.data);
				
				// 将完整的流程卡详细信息保存到全局状态
				// 这里可以直接使用已获取的详细信息，不需要再次调用 API
				if (app.loadProcessCardDetail) {
					await app.loadProcessCardDetail(batchNumber.trim());
				}
			} else {
				formState.processCardId = '';
				app.code = '';
				toast.error('未找到对应的流程卡信息');
				console.error('查询失败:', result.msg || '返回数据格式错误');
			}
		} catch (error) {
			formState.processCardId = '';
			app.code = '';
			toast.error('查询流程卡失败');
			console.error('API调用失败:', error);
		} finally {
			toast.close();
		}
	}
	
	// 监听批次号手动输入变化
	const onBatchNumberChange = () => {
		// 当用户手动输入完成时，也触发查询
		if (formState.batchNumber && formState.batchNumber.length > 0) {
			queryProcessCardId(formState.batchNumber);
		} else {
			formState.processCardId = '';
			app.code = '';
		}
	}

	// 输入框获得焦点时的处理
	const onInputFocus = () => {
		console.log('输入框获得焦点，可以手动输入');
	}

	// 显示手动输入弹窗
	const showManualInput = () => {
		uni.showModal({
			title: '手动输入批次号',
			editable: true,
			placeholderText: '请输入批次号',
			success: function (res) {
				if (res.confirm && res.content) {
					// 用户确认输入
					qrcode(res.content.trim());
				}
			}
		});
	}
	
	onMounted(() => {
		console.log('流程卡扫码页面加载，开始监听 PDA 扫码事件');
		// 监听设备扫码（PDA 物理按键扫码）
		uni.$on("urovo", qrcode);
	});
	
	onUnmounted(() => {
		console.log('流程卡扫码页面卸载，移除 PDA 扫码监听');
		// 移除设备扫码监听
		uni.$off("urovo", qrcode);
	});

	const onSubmit = async () => {
		// 验证批次号和流程卡号是否已填写
		if (!formState.batchNumber) {
			toast.error('请先扫描或填写批次号');
			return;
		}
		
		if (!formState.processCardId) {
			toast.error('请等待流程卡号查询完成');
			return;
		}
		
		// 确保流程卡号保存到全局状态
		app.code = formState.processCardId;
		
		// 显示加载状态
		toast.loading('加载中...');
		
		try {
			// 可以在这里预加载工作数据
			await app.loadWork();
			toast.close();
			
			uni.navigateTo({
				url: '/pages/work_list/work_list',
			});
		} catch (error) {
			toast.close();
			console.error('加载工作数据失败:', error);
			toast.error('加载失败，请检查流程卡号');
		}
	}
	const onScan = () => {
		console.log('点击扫码图标，打开相机扫码');
		uni.scanCode({
			onlyFromCamera: true,
			success: function (res) {
				console.log('相机扫码成功:', res.result);
				qrcode(res.result);
			},
			fail: function (err) {
				console.error('相机扫码失败:', err);
				toast.error('扫码失败');
			}
		});
	}
</script>

<style scoped>
	.layout {
		padding: 16rpx;
	}
</style>